package com.zhangsheng.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhangsheng.constant.OrderConstants;
import com.zhangsheng.entity.model.Order;
import com.zhangsheng.mapper.OrderMapper;
import com.zhangsheng.service.OrderService;
import com.zhangsheng.util.RabbitService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

import static cn.hutool.core.date.DateTime.now;

/**
* @author hp
* @description 针对表【order】的数据库操作Service实现
* @createDate 2023-01-10 14:33:58
*/
@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private RabbitService rabbitService;

    @Override
    @DS("master")
    public Order selectById(Integer id) {
        return getById(id);
    }

    @Override
    @DS("slave1")
    public List<Order> selectByPage(Integer pageNum, Integer pageSize) {
        Page<Order> page = Page.of(pageNum, pageSize);
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        page(page, wrapper);
        log.info("分页查询total：{}" , page.getTotal());
        log.info("分页查询size：{}" , page.getSize());
        log.info("分页查询current：{}" , page.getCurrent());
        List<Order> orders = page.getRecords();
        for (Order order : orders) {
            log.info("order:{}" , order);
        }
        return orders;
    }

    @Override
    @DS("master")
    public boolean createOrder(Order order) {
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        order.setIsdelete(0);
        boolean result = save(order);
        if (result){
            rabbitService.sendMessageToOrderExchange(order.getId() , "10000");
        }
        return result;
    }

    @Override
    @DS("master")
    public boolean closeOrder(Order order) {
        LambdaUpdateWrapper<Order> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(Order::getUpdateTime , now())
                .set(Order::getIsdelete, OrderConstants.ORDER_CANCELED)
                .eq(Order::getId, order.getId());
        return update(wrapper);
    }

}




